import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from './message.entity';
import axios from 'axios';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private messageRepository: Repository<Message>,
  ) { }

  async findAll(query: any = {}): Promise<any[]> {
    try {
      const where: any = {};
      if (query.robotId) {
        where.robotId = query.robotId;
      }
      if (query.userId) {
        where.userId = query.userId;
      }

      // 添加分页
      const take = query.pageSize ? parseInt(query.pageSize) : 20;
      const skip = query.page ? (parseInt(query.page) - 1) * take : 0;

      const [messages, total] = await this.messageRepository.findAndCount({
        where,
        take,
        skip,
        order: {
          createDate: 'DESC'
        }
      });

      // 格式化响应
      return messages.map(message => {
        const formattedMessage: any = {
          ...message,
          msgContent: message.msgContent || '{}',
          msgType: message.msgType || 'text',
          remark: message.remark || '',
        };

        // 格式化日期为字符串
        formattedMessage.createDateString = message.createDate
          ? message.createDate.toISOString()
          : new Date().toISOString();

        formattedMessage.updateDateString = message.updateDate
          ? message.updateDate.toISOString()
          : new Date().toISOString();

        return formattedMessage;
      });
    } catch (error) {
      console.error('获取消息历史失败:', error);
      return []; // 返回空数组而不是抛出错误
    }
  }

  async findOne(id: number): Promise<any> {
    const message = await this.messageRepository.findOne({ where: { id } });

    if (message) {
      // 添加格式化的字符串日期
      const formattedMessage: any = {
        ...message,
        createDateString: message.createDate
          ? message.createDate.toISOString()
          : new Date().toISOString(),
        updateDateString: message.updateDate
          ? message.updateDate.toISOString()
          : new Date().toISOString()
      };

      return formattedMessage;
    }

    return message;
  }

  async create(messageData: any): Promise<Message> {
    try {
      const message = new Message();
      message.robotId = messageData.robotId;
      message.userId = messageData.userId;
      message.msgType = messageData.msgType || 'text';
      message.msgContent = messageData.msgContent;
      message.remark = messageData.remark || '';

      // 添加调试日志
      console.log('保存消息到历史记录:', {
        robotId: message.robotId,
        userId: message.userId,
        msgType: message.msgType,
        contentLength: message.msgContent?.length || 0,
        remark: message.remark
      });

      return await this.messageRepository.save(message);
    } catch (error) {
      console.error('创建消息记录失败:', error.message, error.stack);
      throw new Error('创建消息记录失败: ' + error.message);
    }
  }

  async sendMessage(messageDto: any): Promise<any> {
    try {
      // 发送消息到企业微信机器人
      const response = await axios.post(messageDto.webhook, {
        msgtype: 'markdown',
        markdown: {
          content: messageDto.content
        }
      });

      // 保存消息记录
      if (messageDto.save) {
        await this.create(messageDto);
      }

      return response.data;
    } catch (error) {
      console.error('Failed to send message:', error);
      throw new Error('Failed to send message to WeChat robot');
    }
  }

  async remove(id: number): Promise<void> {
    await this.messageRepository.delete(id);
  }
} 